package com.example.config.handler;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.sun.org.apache.xml.internal.security.exceptions.Base64DecodingException;
import com.sun.org.apache.xml.internal.security.utils.Base64;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.core.Authentication;
//import org.springframework.security.oauth2.common.OAuth2AccessToken;
//import org.springframework.security.oauth2.common.exceptions.UnapprovedClientAuthenticationException;
//import org.springframework.security.oauth2.provider.*;
//import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;
import org.thymeleaf.util.MapUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

//@Component
@Slf4j
public class SuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        log.info("登录成功!");
//        String header = request.getHeader("Authorization");
//        if (header==null && !header.startsWith("Basic ")){
//            throw new UnapprovedClientAuthenticationException("请求头中无client信息");
//        }
//        String[] tokens = extractAndDecodeHeader(header, request);
//        assert tokens.length==2;
//
//        //获取client 和 clientSecret
//        String clientId = tokens[0];
//        String clientSecret = tokens[1];
//
//        //获取clientDetails
//        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(clientId);
//        if (clientDetails==null){
//            throw new UnapprovedClientAuthenticationException("clientId :"+clientId+"不存在");
//        }else if (!StringUtils.equals(clientDetails.getClientSecret(),clientSecret)){
//            throw new UnapprovedClientAuthenticationException("clientSecret:"+clientSecret+"不匹配");
//        }
//        //密码授权 模式，组建authentication
//        TokenRequest tokenRequest = new TokenRequest(new HashMap<String, String>(),clientId,clientDetails.getScope(),"password");
//        OAuth2Request oAuth2Request = tokenRequest.createOAuth2Request(clientDetails);
//        OAuth2Authentication oAuth2Authentication = new OAuth2Authentication(oAuth2Request,authentication);
//        OAuth2AccessToken token = authorizationServerTokenServices.createAccessToken(oAuth2Authentication);
        //判断是json 格式返回 还是 view 格式返回
        //将 authentication 信息打包成json格式返回
//        response.setStatus(200);
        response.sendRedirect("/sys/on");
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(request.getParameterMap()));
    }

    /**
     * 解码请求头
     */
    private String[] extractAndDecodeHeader(String header, HttpServletRequest request) throws IOException {
        byte[] base64Token = header.substring(6).getBytes("UTF-8");
        byte[] decoded = new byte[]{};
        try {
            decoded = Base64.decode(base64Token);
        } catch (Base64DecodingException e) {
            e.printStackTrace();
        }
        String token = new String(decoded, "UTF-8");
        int delim = token.indexOf(":");
        if (delim == -1) {
            throw new BadCredentialsException("Invalid basic authentication token");
        } else {
            return new String[]{token.substring(0, delim), token.substring(delim + 1)};
        }
    }
}

